// 3.5 发送sdp offer
use reqwest::Client;
use serde_json::json;
use crate::api::get_stream_token::get_stream_token;
use crate::api::get_session_id::get_session_id;
use anyhow::{anyhow, Result};

pub async fn send_sdp(sdp: String) -> Result<()> {
    let client = Client::new();
    let stream_token = get_stream_token().await.unwrap();
    let Authorization = format!("Bearer {}", stream_token);

    let session_id = get_session_id(None).await.unwrap();
    let url = format!("https://uks.core.gssv-play-prodxhome.xboxlive.com/v5/sessions/home/{session_id}/sdp");
//     let payload = format!(r#"{{
//   "messageType": "offer",
//   "sdp": {sdp},
//   "configuration": {{
//     "chatConfiguration": {{
//       "bytesPerSample": 2,
//       "expectedClipDurationMs": 20,
//       "format": {{
//         "codec": "opus",
//         "container": "webm"
// }},
//       "numChannels": 1,
//       "sampleFrequencyHz": 24000
// }},
//     "chat": {{
//       "minVersion": 1,
//       "maxVersion": 1
// }},
//     "control": {{
//       "minVersion": 1,
//       "maxVersion": 3
// }},
//     "input": {{
//       "minVersion": 1,
//       "maxVersion": 8
// }},
//     "message": {{
//       "minVersion": 1,
//       "maxVersion": 1
// }}
// }}
// }}"#);



    // let payload = payload.replace("\n", "");



 let payload = json!({
        "messageType": "offer",
        "sdp": sdp,
        "configuration": {
            "chatConfiguration": {
                "bytesPerSample": 2,
                "expectedClipDurationMs": 20,
                "format": {
                    "codec": "opus",
                    "container": "webm"
                },
                "numChannels": 1,
                "sampleFrequencyHz": 24000
            },
            "chat": {
                "minVersion": 1,
                "maxVersion": 1
            },
            "control": {
                "minVersion": 1,
                "maxVersion": 3
            },
            "input": {
                "minVersion": 1,
                "maxVersion": 8
            },
            "message": {
                "minVersion": 1,
                "maxVersion": 1
            }
        }
    });
        let response = client.post(url)
        .header("Accept", "application/json")
        .header("Content-Type", "application/json")
        .header("Authorization", Authorization)
        .body(payload.to_string())
        .send().await.unwrap();
    let response_code = response.status().as_u16();
    if (response_code < 200 || response_code > 299) {
        return Err(anyhow!("Failed to send SDP. Response code: {response_code}"));
    }
    return Ok(());
}